﻿<%@ WebHandler Language="C#" Class="KPIReport.Web.AjaxHandler.Administration.UserManagement.sUserhandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using System.Text;

using KPIReport.Library.DataAccess.Administration;
using KPIReport.Library.DomainObject.Administration;
using KPIReport.Library.DataAccess.Administration.UserManagement;
using KPIReport.Library.DomainObject.Administration.UserManagement;

using KPIReport.Library.Enum;
using KPIReport.Web.Support;

using Newtonsoft.Json.Linq;

//using KPIReport.Library.DataAccess.Administration.Catalog;
//using KPIReport.Library.DomainObject.Administration.Catalog;

namespace KPIReport.Web.AjaxHandler.Administration.UserManagement
{

    public class sUserhandler : BaseHandler
    {
        //private recUserTypeRepo userTypeDal = new recUserTypeRepo(ConfigurationManager.ConnectionStrings["KPIReportConn"].ConnectionString);
        private recUserRepo userDal = new recUserRepo(ConfigurationManager.ConnectionStrings["KPIReportConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["KPIReportConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
            string jsonString = string.Empty;

            jsonString = context.Server.UrlDecode(sr.ReadToEnd());

            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                case ("changepassword"):
                    context.Response.Write(UpdatePassword(context));
                    break;
                case ("getpassword"):
                    context.Response.Write(GetPassword(context));
                    break;
                case ("cekusercode"):
                    context.Response.Write(cekusercode(context));
                    break;
                case ("getafterlogin"):
                    context.Response.Write(GetAfterLoginPassword(context));
                    break;
                case ("resetpassword"):
                    context.Response.Write(ResetPassword(context, jObj));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            
            try
            {
                string UserCode = (string)jo["UserCode"];

              
                    bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                    recUser obj = new recUser();
                    obj.UserName = (string)jo["UserName"];
                    obj.UserCode = (string)jo["UserCode"];
                    if (jo["UserCode"].ToString() != "")
                        obj.Email = (string)jo["UserCode"];
                    obj.IsActive = isActive;
                    ////if (jo["CabangID"].ToString() != "")
                    ////{
                    ////    //obj.CabangID = Convert.ToInt32(jo["CabangID"].ToString());
                    ////}

                    //if (jo["DepartmentID"].ToString() != "")
                    //{
                    //    obj.DepartmentID = Convert.ToInt32(jo["DepartmentID"].ToString());
                    //}
                 

                    //if (jo["Mobile"].ToString() != "")
                    //    obj.Mobile = (string)jo["Mobile"];
                    obj.Password = (string)jo["Password"].ToString().ToUpper() ;

                    obj.CreatedDate = DateTime.Now;
                    obj.CreatedBy = base.UserLoggedIn;

                    userDal.Save(obj);
                    helper.Message = "Data berhasil di simpan !";
                    helper.IsSuccess = true;
              
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                bool isActive = jo["IsActive"] == null ? false : ((string)jo["IsActive"] == "1" ? true : false);
                recUser obj = new recUser();
                obj.UserID = Convert.ToInt32(jo["UserID"]);
                obj.UserName = (string)jo["UserName"];
                obj.UserCode = (string)jo["UserCode"];
                if (jo["UserCode"].ToString() != "")
                    obj.Email = (string)jo["UserCode"];
                obj.IsActive = isActive;

                //if (jo["CabangID"].ToString() != "")
                //{
                //    //obj.CabangID = Convert.ToInt32(jo["CabangID"].ToString());
                //}

                //if (jo["DepartmentID"].ToString() != "")
                //{
                //    obj.DepartmentID = Convert.ToInt32(jo["DepartmentID"].ToString());
                //}
                
                //obj.Mobile = (string)jo["Mobile"];
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;
                userDal.Update(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["UserID"];

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    int intID = Convert.ToInt32(id);
                    userDal.Delete(intID);
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di hapus !";
            }
            catch (Exception ex)
            {
                helper.Message = ex.Message;
                if (ex.Message.Contains("FK_recUserSector_recUser") || ex.Message.Contains("FK_recUserRole_recUser"))
                {
                    helper.Message = "User mempunyai  role, hapus terlebih dahulu!";
                }
                helper.IsSuccess = false;
                
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            string parameters = Helper.JqGridFilterToSQLParams(context); ;
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recUser.Fields.UserName : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recUser> pagedList = null;

            try
            {
                    totalCount = Convert.ToInt32(userDal.SelectScalar(SQL.Function.Aggregate.Count, recUser.Fields.UserID, parameters));
                    decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                    totalPages = Convert.ToInt32(dc);
                    pagedList = userDal.GetList(pageSize, page, sidx, sord, parameters);
               
                }
            catch (Exception ex)
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = ex.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }
            finally
            {

            }
            

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,

            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);
        }

       
        

        #endregion

        private string UpdatePassword(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                int user_id = Convert.ToInt32(context.Request.Params["id"]);
                string new_password = Helper.CreatePasswordHash(context.Request.Params["password"]);

                userDal.Update(user_id, new_password, base.UserLoggedIn);

                helper.Message = "Password berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Change Password";
                log.LogMessage = helper.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetPassword(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            StringBuilder sb = new StringBuilder();

            try
            {
                var UserID = Convert.ToInt32(context.Request.Params["id"]);

                recUser user = userDal.GetById(UserID);

                sb.Append("{");
                sb.AppendFormat("  {0}Password{0}:{0}{1}{0}", "\"", user.Password);
                sb.Append(",");
                sb.AppendFormat("  {0}UserName{0}:{0}{1}{0}", "\"", Helper.CreatePasswordHash(user.UserName));
                sb.Append("}");

                helper.IsSuccess = true;
                helper.Message = "Got password successfully!";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Get Password";
                log.LogMessage = helper.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            if (helper.IsSuccess)
                return sb.ToString();
            else
                return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        private string GetAfterLoginPassword(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            StringBuilder sb = new StringBuilder();

            try
            {
                var UserID = Convert.ToInt32(context.Request.Params["id"]);

                recUser user = userDal.GetById(UserID);

                sb.Append("{");
                sb.AppendFormat("  {0}Password{0}:{0}{1}{0}", "\"", user.Password);
                sb.Append(",");
                sb.AppendFormat("  {0}UserCode{0}:{0}{1}{0}", "\"", user.UserName);
                sb.Append("}");

                helper.IsSuccess = true;
                helper.Message = "Got password successfully!";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Get Password";
                log.LogMessage = helper.Message;
                log.LogSource = "sUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            if (helper.IsSuccess)
                return sb.ToString();
            else
                return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string cekusercode(HttpContext context)
        {
            
            string code =  context.Request.Params["code"].ToString();
            bool result = false;
            result = userDal.CheckDataByUserCode(code);

            StringBuilder sbProject = new StringBuilder();

            sbProject.Append("{");
            sbProject.AppendFormat("  {0}Sector{0}:{0}{1}{0}", "\"",result);
            sbProject.Append("}");

            return(sbProject.ToString());
           
        }

        private string ResetPassword(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                var strId = (string)jo["ID"];
                recUser obj = new recUser();
                List<recUser> list = new List<recUser>();

                string[] ids = strId.Split(',');
                foreach (string id in ids)
                {
                    //int intID = Convert.ToInt32(id);
                    //JobDescriptionDal.UpdateApprove(intID);

                    obj =userDal.GetById(Convert.ToInt32(id));
                    if (obj != null)
                    {
                        obj.UpdatedBy = base.UserLoggedIn;
                        obj.UpdatedDate = DateTime.Now;

                        obj.Password = Helper.CreatePasswordHash("welcome").ToUpper();
                        list.Add(obj);
                    }
                }

                userDal.ResetPassword(list);

                helper.IsSuccess = true;
                helper.Message = "Reset password berhasil !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Reset Password";
                log.LogMessage = helper.Message;
                log.LogSource = "recUserhandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

    }
}